import { Toast,Indicator } from 'mint-ui';
import {axiosPost} from '../../assets/api';
import CosCloud from '../../../static/cos-js-sdk-v4';
import Client from './common';
//全部好友资料
const getAllFriend = (identifier) => {
    return new Promise((resolve,reject) =>{
    let options = {
      From_Account: identifier,
      TimeStamp: 0,
      StartIndex: 0,
      GetCount: 100, //totalCount,
      LastStandardSequence: 0,
      TagList: [
        "Tag_Profile_IM_Nick",
        "Tag_Profile_IM_SelfSignature", //个性签名
        "Tag_Profile_IM_Image", //头像
        "Tag_Profile_IM_Gender", //性别
        "Tag_Profile_IM_AllowType", //加好友验证方式
        "Tag_Profile_IM_Location", //所在地
        "Tag_Profile_IM_BirthDay", //生日
        "Tag_Profile_IM_MsgSettings" //消息设置 置0表示接收消息，置1则不接收消息
      ]
    };
    webim.getAllFriend(
      options,
      resp => {
        if (resp.FriendNum > 0) {
            resolve(resp);
        }else{
            resolve(null);
        }
      },
      err => {
        reject(err.ErrorInfo);
      }
    );
   });
}
  
//读取用户个人资料
const getProfilePortrait = idArr => {
    return new Promise((resolve,reject) => {
    let tag_list = [
        "Tag_Profile_IM_Nick",//昵称
        "Tag_Profile_IM_Gender",//性别
        "Tag_Profile_IM_AllowType",//加好友方式
        "Tag_Profile_IM_Image"//头像
    ];
    let options = {
        'To_Account': idArr,
        'TagList': tag_list
    };
    webim.getProfilePortrait(
        options,
        resp => {
            let data = [];
            if (resp.UserProfileItem && resp.UserProfileItem.length > 0) {
                for (let i in resp.UserProfileItem) {
                    let to_account = resp.UserProfileItem[i].To_Account;
                    let nick = null, gender = null, allowType = null,imageUrl=null;
                    for (let j in resp.UserProfileItem[i].ProfileItem) {
                        switch (resp.UserProfileItem[i].ProfileItem[j].Tag) {
                            case 'Tag_Profile_IM_Nick':
                                nick = resp.UserProfileItem[i].ProfileItem[j].Value;
                                break;
                            case 'Tag_Profile_IM_Gender':
                                switch (resp.UserProfileItem[i].ProfileItem[j].Value) {
                                    case 'Gender_Type_Male':
                                        gender = '男';
                                        break;
                                    case 'Gender_Type_Female':
                                        gender = '女';
                                        break;
                                    case 'Gender_Type_Unknown':
                                        gender = '未知';
                                        break;
                                }
                                break;
                            case 'Tag_Profile_IM_AllowType':
                                switch (resp.UserProfileItem[i].ProfileItem[j].Value) {
                                    case 'AllowType_Type_AllowAny':
                                        allowType = 1; //'允许任何人';
                                        break;
                                    case 'AllowType_Type_NeedConfirm':
                                        allowType = 2; //'需要确认';
                                        break;
                                    case 'AllowType_Type_DenyAny':
                                        allowType = 3; //'拒绝任何人';
                                        break;
                                    default:
                                        allowType = '需要确认';
                                        break;
                                }
                                break;
                            case 'Tag_Profile_IM_Image':
                                imageUrl = resp.UserProfileItem[i].ProfileItem[j].Value;
                                break;
                        }
                    }
                    data.push({
                        'To_Account': to_account,
                        'Nick': webim.Tool.formatText2Html(nick),
                        'Gender': gender,
                        'AllowType': allowType,
                        'Image': imageUrl
                    });
                    resolve(data);
                }
            }
        },
        err => {
            reject(err.ErrorInfo);
            //alert(err.ErrorInfo);
        }
    );
  });
};

// 我的黑名单
const getBlackList = identifier => {
    return new Promise((resolve,reject) => {
    let options = {
      'From_Account': identifier,
      'StartIndex': 0,
      'MaxLimited': 100,
      'LastSequence': 0
    };

    webim.getBlackList(
      options,
      resp => {
        let arr = [];
        if (resp.BlackListItem && resp.BlackListItem.length > 0) {
          for (let i = 0; i < resp.BlackListItem.length; i++) {
            arr.push(resp.BlackListItem[i].To_Account)
          }
        }
        resolve(arr);
      },
      err => {
        reject(err.ErrorInfo);
      }
    );
   });
  };

// 加入黑名单
const addBlack = (identifier,toId) =>{
    return new Promise((resolve,reject) => {
        let options = {
            'From_Account': identifier,
            'To_Account': [toId]
        };
        webim.addBlackList(
            options,
            resp => {
                resolve(resp);
                //Toast('加入黑名单成功');
            },
            err => {
                reject(err);
                //Toast('加入黑名单失败');
            }
        );
    });
};

const deleteBlack = (identifier,toId) =>{
    return new Promise((resolve,reject) => {
      let options = {
        'From_Account': identifier,
        'To_Account': [toId]
      };
      webim.deleteBlackList(
        options,
        resp => {
          //Toast('已将该好友移出黑名单');
          resolve(resp);
        },
        err => {
          //Client.errInfo();
          reject(err);
        }
      );
    });
}
//自定义
//obj个人资料与接收人ID及消息类型对象;cusData收藏或分享数据
const sendCustom = (obj,cusData)=> {
    let selSess = new webim.Session(obj.selType, obj.selToID, obj.selToID, '', Math.round(new Date().getTime() / 1000));
    let msg = new webim.Msg(selSess, true, -1, -1, -1, obj.identifier, 0, obj.identifierNick);
    let custom_obj = new webim.Msg.Elem.Custom(cusData.CollectUrl, cusData.CollectTitle, cusData.CollectImgUrl);
    msg.addCustom(custom_obj);
    msg.sending = 1;
    webim.sendMsg(msg, resp => {
        Toast('发送消息成功');
    }, err => {
        Toast('发送消息失败');
    });
}

//读取群组成员
const getGroupMemberInfo = group_id=> {
    return new Promise((resolve,reject) => {
    let options = {
        'GroupId': group_id,
        'Offset': 0, //必须从0开始
        'Limit': 2000,
        'MemberInfoFilter': [
            'Account',
            'Role',
            'JoinTime',
            'LastSendMsgTime',
            'ShutUpUntil'
        ]
    };
    webim.getGroupMemberInfo(
            options,
            resp => {
                if (resp.MemberNum <= 0) {
                    //alert('该群组目前没有成员');
                    return;
                }
                resolve(resp);
            },
            err => {
                reject(err);
            }
    );
   });
};

//获取我的群组
const getMyGroup = identifier => {
    return new Promise((resolve,reject) => {
    let options = {
        'Member_Account': identifier,
        'Limit': 200,
        'Offset': 0,
        //'GroupType':'',
        'GroupBaseInfoFilter': [
            'Type',
            'Name',
            'Introduction',
            'Notification',
            'FaceUrl',
            'CreateTime',
            'Owner_Account',
            'LastInfoTime',
            'LastMsgTime',
            'NextMsgSeq',
            'MemberNum',
            'MaxMemberNum',
            'ApplyJoinOption',
            'ShutUpAllMember'
        ],
        'SelfInfoFilter': [
            'Role',
            'JoinTime',
            'MsgFlag',
            'UnreadMsgNum'
        ]
    };
    webim.getJoinedGroupListHigh(
            options,
            resp => {
                if (!resp.GroupIdList || resp.GroupIdList.length == 0) {
                    //alert('你目前还没有加入任何群组');
                    return;
                }
                resolve(resp.GroupIdList);
            },
            err => {
                reject(err);
            }
    );
  });
};

//读取群组基本资料-高级接口
const getGroupInfo = function(group_id, cbOK, cbErr) {
    let options = {
        'GroupIdList': [
            group_id
        ],
        'GroupBaseInfoFilter': [
            'Type',
            'Name',
            'Introduction',
            'Notification',
            'FaceUrl',
            'CreateTime',
            'Owner_Account',
            'LastInfoTime',
            'LastMsgTime',
            'NextMsgSeq',
            'MemberNum',
            'MaxMemberNum',
            'ApplyJoinOption',
            'ShutUpAllMember'
        ],
        'MemberInfoFilter': [
            'Account',
            'Role',
            'JoinTime',
            'LastSendMsgTime',
            'ShutUpUntil'
        ]
    };
    webim.getGroupInfo(
        options,
        resp => {
            if (resp.GroupInfo[0].ShutUpAllMember == 'On') {
                //alert('该群组已开启全局禁言');
            }
            if (cbOK) {
                cbOK(resp);
            }
        },
        err => {
            //alert(err.ErrorInfo);
        }
    );
};

const getLocalPic = (e,results) => {
    if(!e){
        return;
    }
    let localUrl;
    let reader = new FileReader(),
    getfile = e.srcElement.files[0];
    let fileLimit = 1024 * 1024 * 20;  // 1M图片限制
    if (!getfile.type.includes('image')) {
        Toast("请上传图片格式的文件")
        return false;
    }
    if (getfile.size > fileLimit) {
        Toast('请上传20M以内的图片')
        return false;
    }
    reader.onload = (getfile => {
        return e => {
            results&&results(e.srcElement.result);
        };
    })(getfile);
    reader.readAsDataURL(getfile);
};
//图片上传
const changePicFile = e => {
    return new Promise((resolve,reject) => {
        let apiname = "upload/uploadHeadPic";
        axiosPost({
            data: {
                "fileEtension": "jpg",
                "signType": 0
            },
            url: apiname + '?token=123&appSecret=8888',
            onSuccess:res=> {
                let cosdata = res.Result;
                console.log('res.Result',);
                let cos = new CosCloud({
                appid: cosdata.appid, // APPID 必填参数
                bucket: cosdata.bucket, // bucketName 必填参数
                region: cosdata.region, // 地域信息 必填参数 华南地区填gz 华东填sh 华北填tj
                getAppSign: callback => {
                    callback(cosdata.AppSign);
                },//多次签名 可使用多次
                getAppSignOnce: callback=> {
                    callback(cosdata.AppSignOnce);
                }
                });
                uploadFile(e,cosdata,cos).then(resp=>{
                    resolve(resp);
                });
            },
            onFailure:res=> {
                //Client.errInfo();
            }
        });
    });
};

//文件上传
const uploadFile = (e,cosdata,cos) =>{
    return new Promise((resolve,reject) => {
        let successCallBack = result => {
        Indicator.close();
        if(result.code !== 0){
            Toast('图片上传失败');
            return;
        }else{
            //_this.userMes.Tag_Profile_IM_Image = result.data.access_url;
            resolve(result.data.access_url);
            Toast('图片上传成功');
        }
        };

        let errorCallBack = result => {
        Indicator.close();
        result = result || {};
        console.log('request error:', result && result.message);
        };

        let progressCallBack = (curr, sha1) => {
        };
        let lastTaskId;
        let taskReady = taskId => {
            lastTaskId = taskId;
        };
        let file = e.target.files[0];
        // 分片上传过程可能会有 op=upload_slice_list 的 POST 请求返回 404，不会影响上传
        Indicator.open();
        cos.uploadFile(successCallBack, errorCallBack, progressCallBack, cosdata.bucket,
        cosdata.fileName, file, 0, taskReady);//insertOnly==0 表示允许覆盖文件 1表示不允许
        return false;
    });
};

//我的收藏
const myColect = loginInfo => {
    return new Promise((resolve,reject) => {
        axiosPost({
        data: {
            ...loginInfo.checkLogin,
            Identifier: loginInfo.identifier,
            Type: "1"
        },
        url:"TerminalCollect/GetCollectInformationList?token=xxxxx&appsecret=XXXXX",
        onSuccess: res => {
            console.log("我的收藏", res);
            if (res.Result) {
                res.Result.forEach((item,index)=>{
                    let times = new Date(item.Datetime),
                        transTime = times.getFullYear() + '-' + Client.formatData(times.getMonth() + 1) + '-' + Client.formatData(times.getDate());
                    item.Datetime = transTime;
                    if(index == 0 || (index > 0 && item.Datetime != res.Result[index-1].Datetime)){
                        item.distanTime = item.Datetime;
                    }    
                });
                resolve(res.Result);
            }
        },
        onFailure: err => {
            reject(err);
        }
        });
    });
};

//删除一条收藏
const deleteCollect = (loginInfo,CollectId) => {
    return new Promise((resolve,reject) => {
        axiosPost({
            data: {
                ...loginInfo.checkLogin,
                Identifier: loginInfo.identifier,
                Sig: loginInfo.userSig,
                CollectId: CollectId
            },
            url:"TerminalCollect/DeleteCollectInformation?token=xxxxx&appsecret=XXXXX",
            onSuccess: res => {
                resolve(res);
                console.log("删除收藏成功", res);
            },
            onFailure: err => {
                reject(err);
                console.log("err", err);
            }
        });
    });
};    
//读取不同类型的关注
const loadFocus = (loginInfo,type) => {
    //type 0表示我的关注 1表示互相关注 2表示我的粉丝
    let urls;
    if(type == 0){
        urls = 'TerminalUserAttention/GetMyattentionList?token=xxxxx&appsecret=XXXXX';
    }else if(type == 1){
        urls = 'TerminalUserAttention/GetMutualConcernList?token=xxxxx&appsecret=XXXXX';
    }else if(type == 2){
        urls = 'TerminalUserAttention/GetMyFansList?token=xxxxx&appsecret=XXXXX';
    };
    return new Promise((resolve,reject) => {
        axiosPost({
            data: {...loginInfo.checkLogin,Identifier:loginInfo.identifier,PageSize:100,PageIndex:1},
            url: urls,
            onSuccess: res=> {
                if(res.Result){
                    resolve(res.Result);
                }
            },
            onFailure:err=> {
                reject(err);
                console.log('err',err);		
            }
        });
    });
};

//关注或取消关注
//1关注 3取消关注
const changeFocus = (loginInfo,toId,type) => {
    let focusURL;
    if(typeof type == 'undefined' || type == 1){
        focusURL = "TerminalUserAttention/AddAttention?token=xxxxx&appsecret=XXXXX";
    }else{
        focusURL = "TerminalUserAttention/CancelAttention?token=xxxxx&appsecret=XXXXX";
    }
    return new Promise((resolve,reject) => {
        axiosPost({
            data: {
                ...loginInfo.checkLogin,
                Identifier: loginInfo.identifier,
                Sig: loginInfo.userSig,
                ToIdentifier: toId
            },
            url: focusURL,
            onSuccess: res => {
                resolve(res);
            },
            onFailure: err => {
                reject(err);
            }
        });
    });
}

const Chat = {
    getAllFriend,
    getGroupInfo,
    getProfilePortrait,
    getBlackList,
    addBlack,
    deleteBlack,
    getGroupMemberInfo,
    getMyGroup,
    sendCustom,
    getLocalPic,
    changePicFile,
    myColect,
    deleteCollect,
    loadFocus,
    changeFocus
}
export default Chat